{% extends 'index.html' %} 
{% block ace-content %}
<!-- ACE Editor -->   
<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<link href="/static/dist/css/fileinput.css" media="all" rel="stylesheet" type="text/css" />
<script src="/static/dist/js/fileinput.js" type="text/javascript"></script>
<style type="text/css">
	#compile-editor {
		/* position: absolute; */
	width: 100%;
	height: 400px;
   }	
</style>
{% endblock %}
{%block page-content %}
<div id="page-wrapper">

	<div class="row">
		<div class="col-lg-12">
			<h1 class="page-header">
				<i class="fa fa-tasks"></i>&nbsp;
				<code>SQL上线申请</code>
			</h1>
		</div>
		<!-- /.col-lg-12 -->
	</div>


	<div class="row">
			<div class="col-lg-12">
				<div class="panel panel-default">
					<div class="panel-heading"><i class="fa fa-history"></i> 配置需要上线的SQL</div>
					<div class="panel-body">
					<div class="row">
						<div class="col-lg-6">
							<legend>
								<i class="fa  fa-paper-plane"></i> SQL信息
							</legend>
							<form role="form" method="post" id="audit_sql_order" enctype="multipart/form-data">
								{% csrf_token %}
								<div class="form-group">
 									<label>用途<i class="fa fa-info-circle" data-toggle="tooltip" title="说明用途"></i></label>
									<textarea class="form-control" rows="3" id="order_desc"></textarea>

								</div>	
								<div class="form-group" >			 		             
									<label >SQL类型: </label>	
									<div class="btn-group btn-group-sm">
										<button type="button" class="btn btn-default" onclick="setSQLMode('onlineSql')"><a>在线编写</a></button>
										<button type="button" class="btn btn-default" onclick="setSQLMode('uploadSQL')"><a>上传SQL</a></button>
									</div>
								</div> 								
								<div class="form-group" id="onlineSql">
									<label>上线SQL<i class="fa fa-info-circle" data-toggle="tooltip" title="申请上线的SQL语句"></i></label>
									<div id="compile-editor" class="ace_editor"></div>
									<p class="help-block">例如：insert into tablename (xxx,xxx,xxx) values (xxx,xxx,xxx);</p>								
								</div>	
								<div class="form-group" id="uploadSQL" style="display:none;">
									<label>上传SQL<i class="fa fa-info-circle" data-toggle="tooltip" title="申请上线的SQL文件"></i></label>
									<input type="file" class="file" id="order_file"  value="" />								
								</div>														
								<lable id="auditContol"><button type="button" class="btn btn-default" onclick="auditSqlOrder(this,'audit')" >审核</button></lable>
								<button type="reset" class="btn btn-default">撤销</button>
						</div>
						<!-- /.col-lg-6 (nested) -->
						<div class="hr hr32 hr-dotted"></div>
						<div class="col-lg-6">
							<legend>
								<i class="fa  fa-paper-plane-o"></i> 数据库选择
							</legend>
							
							<div class="form-group" >			 		             
								<label >环境类型</label>	
								<select class="form-control"  name="ops_env" id="ops_env" onchange="javascript:oBtEnvSelect();">
									<option name="ops_env" value="" selected="selected">选择一个类型进行操作</option>
									<option name="ops_env" value="test" >测试</option>
									<option name="ops_env" value="prod" >生产</option>
								</select>		
							</div>    
							<div class="form-group" >			 		             
								<label >所属项目</label>	
								<select class="form-control"  name="ops_project" id="ops_project" onchange="javascript:oBtProjectSelect();">
									<option name="ops_project" value="" selected="selected">选择一个项目</option>
									{% for ds in projectList %}
										<option value="{{ds.id}}" name="ops_project">{{ds.project_name}}</option>
									{% endfor %}
								</select>		
							</div> 
							<div class="form-group">
								<label >业务类型</label>
								<select class="form-control" name="ops_service" id="ops_service" onchange="javascript:oBtServiceSelect();">
									   <option selected="selected" value="">请选择一个类型</option>								   							
								</select>
							</div>								 							                                 	 
                                
							<div class="form-group" >			 		             
								<label >数据库</label>	
								<select class="form-control"  name="order_db" id="order_db">
									<option name="order_db" value="" selected="selected">选择一个类型进行操作</option>
								</select>		
							</div>							
											
							<div class="form-group">
								<label>执行人<i class="fa fa-info-circle"
									data-toggle="tooltip" title="工单发送给谁执行"></i></label> 
									<select class="form-control" data-live-search="true" id="order_executor" name="order_executor" required> 
										<option name="order_executor" value="">选择一个执行者</option> 
										{% for ds in userList %}
											<option name="order_executor" value="{{ds.id}}">{{ds.username}}</option> 
										{% endfor %}
									</select>								
								<p class="help-block">例如：admin</p>
							</div>
						</div>
						<div class="col-lg-6" id="auditResultDiv" style="display:none;">
							<legend>
								<i class="fa  fa-spinner  "></i> 审核结果
							</legend>
							<div>
                                <table class="table table-hover" id='auditResult'>
				                    <thead>
				                        <tr>
				                            <th>#</th>
				                            <th>SQL</th>
				                            <th>影响行</th>
				                            <th>错误原因</th>
				                        </tr>
				                	</thead>                             
                                </table>								
							</div>
						</div>						
						<!-- /.col-lg-6 (nested) -->
						<div class="hr hr32 hr-dotted"></div>
						</form>
					</div>

					</div>
					<div class="panel-footer"></div>
				</div>
			</div>

	</div>
	


</div>



<script type="text/javascript">

{% if errinfo %}
	window.wxc.xcConfirm("{{errinfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}


	$("#order_file").fileinput({
		language : 'zh',
 		showUpload : false, 
 	    uploadUrl: '#', // you must set a valid URL here else you will get an error 
   	    allowedFileExtensions : [".sql",".txt"], 
   	 	previewFileType:"pdf",
  	  	allowedFileTypes: ["text"],
	    overwriteInitial: false,
	    maxFileSize: 2000,
	    maxFilesNum: 10,
/* 	    dropZoneTitle:"暂不支持拖拽文件上传...", */
	    dropZoneEnabled: false,
	    slugCallback: function(filename) {
	        return filename.replace('(', '_').replace(']', '_');
	    }
	});

	function uploadSqlFile(target,id) { 
		var isIE = /msie/i.test(navigator.userAgent) && !window.opera; 
		var fileSize = 0; 
		var filetypes =[".sql",".txt"]; 
		var filepath = target.value; 
		var filemaxsize = 1024*10;//2M 
		if(filepath){ 
			var isnext = false; 
			var fileend = filepath.substring(filepath.indexOf(".")); 
			if(filetypes && filetypes.length>0){ 
				for(var i =0; i<filetypes.length;i++){ 
					if(filetypes[i]==fileend){ 
						isnext = true; 
						break; 
					} 
				} 
			} 
			if(!isnext){ 
				target.value =""; 
				return false; 
			} 
		}else{ 
			return false; 
		} 
		if (isIE && !target.files) { 
			var filePath = target.value; 
			var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); 
			if(!fileSystem.FileExists(filePath)){ 
				window.wxc.xcConfirm("附件不存在，请重新上传", window.wxc.xcConfirm.typeEnum.error);
				return false; 
			} 
			var file = fileSystem.GetFile (filePath); 
			fileSize = file.Size; 
		} else { 
			fileSize = target.files[0].size; 
		} 
	
		var size = fileSize / 1024; 
		if(size > filemaxsize){ 
			window.wxc.xcConfirm("sql文件大小不能大于"+filemaxsize/1024+"M！", window.wxc.xcConfirm.typeEnum.error);
			target.value =""; 
			return false; 
		} 
		if(size <= 0){ 
			window.wxc.xcConfirm("附件大小不能为0M！", window.wxc.xcConfirm.typeEnum.error);
			target.value =""; 
			return false; 
		} 
	} 


	function oBtEnvSelect(){
		$('#order_db option:selected').empty();
		$("#ops_service").val("");
	}
	var order_type = 'online';
	function setSQLMode(id){
		if (id=='onlineSql'){
			document.getElementById("onlineSql").style.display = "";
			document.getElementById("uploadSQL").style.display = "none"; 
			order_type = 'online';
		}
		else{
			document.getElementById("onlineSql").style.display = "none";
			document.getElementById("uploadSQL").style.display = ""; 	
			order_type = 'file';
		}
		
	}
	
	function oBtProjectSelect(){
		   $('#ops_service').removeAttr("disabled");
		   var obj = document.getElementById("ops_project"); 
		   var index = obj.selectedIndex;
		   var projectId = obj.options[index].value; 
		   if ( projectId > 0){	 
				$.ajax({
					dataType: "JSON",
					url:'/api/project/'+ projectId + '/', //请求地址
					type:"GET",  //提交类似
					success:function(response){
						var binlogHtml = '<select class="form-control" name="ops_service" id="ops_service" onchange="javascript:oBtServiceSelect();" required><option selected="selected" name="ops_service" value="">请选择业务类型</option>'
						var selectHtml = '';
						for (var i=0; i <response["service_assets"].length; i++){
							 selectHtml += '<option name="ops_service" value="'+ response["service_assets"][i]["id"] +'">' + response["service_assets"][i]["service_name"] + '</option>' 
						};                        
						binlogHtml =  binlogHtml + selectHtml + '</select>';
						document.getElementById("ops_service").innerHTML= binlogHtml;	
							
					},
				});	
		   }
		   else{
			   $('#ops_service').attr("disabled",true);
		   }

	}
	
	function oBtServiceSelect(){
	 	   $('#order_db').removeAttr("disabled");
		   var obj = document.getElementById("ops_service"); 
		   var env = $('#ops_env option:selected').val();	
		   var index = obj.selectedIndex;
		   var sId = obj.options[index].value; 
		   if ( sId  > 0){	 
				$.ajax({
					dataType: "JSON",
					url:'/db/sql/ops/', //请求地址
					type:"POST",  //提交类似
					data:{
						'model':'querydb',
						'db_service':sId,
						'db_env':env,
					},  //提交参数
					success:function(response){
						var dbHtml = '<select class="form-control"  name="ops_db" id="order_db" onchange="javascript:oBtDbsSelect();"><option name="order_db" value="" selected="selected">选择一个数据库进行操作</option>'
						var selectHtml = '';
						for (var i=0; i <response["data"].length; i++){
							 selectHtml += '<option name="order_db" value="'+ response["data"][i]['id'] +'">' + response["data"][i]['db_name'] +  '(' + response["data"][i]['db_host'] + ')' +  '-(' + response["data"][i]['db_mark'] + ')' + '</option>' 
						};                        
						dbHtml =  dbHtml + selectHtml + '</select>';
						document.getElementById("order_db").innerHTML= dbHtml;
							
					},
				});	
		   }
		   else{
			   $('#order_db option:selected').empty();
			   $('#order_db').attr("disabled",true);
		   }

	}	
	

	function setAceEditMode(model) {
		var editor = ace.edit("compile-editor");
		require("ace/ext/old_ie");
		var langTools = ace.require("ace/ext/language_tools");
		editor.setTheme("ace/theme/monokai");
		editor.getSession().setMode("ace/mode/" + model);
		editor.setShowPrintMargin(false);
		editor.setOptions({
		    enableBasicAutocompletion: true,
		    enableSnippets: true,
		    enableLiveAutocompletion: true
		}); 
				 
	};
	setAceEditMode("mysql");

	$(document).ready(function() {
	    $('#taskTableList').DataTable();
	} );  
    $(function () { 
    	$("[data-toggle='popover']").popover();
    });	
    
	function auditSqlOrder(obj,op) {	
		var btnObj = $(obj);
		var required = ["order_db","order_executor"];
		btnObj.attr('disabled',true);
			var server_data = {};
			var form = document.getElementById('audit_sql_order');
			for (var i = 0; i < form.length; ++i) {
				var name = form[i].name;
				var value = form[i].value;	
				idx = $.inArray(name, required);						
				if (idx >= 0 && value.length == 0){
					window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
					btnObj.removeAttr('disabled');
					return false;
				};					
			};				
			var editor = ace.edit("compile-editor");
		    var order_sql = editor.getSession().getValue(); 
		    if  (order_sql.length <= 5 && order_type=='online'){
		    	window.wxc.xcConfirm("请检查SQL文件是否为空~", window.wxc.xcConfirm.typeEnum.error);
				btnObj.removeAttr('disabled');
				return false;		    	
		    };
		    var formData = new FormData();
		    if (order_type=='file'){
		    	formData.append('order_file', $('#order_file')[0].files[0]);
		    };
		    formData.append('type','audit');
		    formData.append('order_desc',$('#order_desc').val());
		    formData.append('order_db',$('#order_db option:selected').val());
		    formData.append('order_executor',$('#order_executor option:selected').val());
		    formData.append('order_sql',order_sql);
		    formData.append('order_type',order_type);
			$.ajax({
/* 				dataType: "JSON", */
				url:'/order/sql/apply/', //请求地址
				type:"POST",  //提交类似
			    processData: false,
			    contentType: false,				
				data:formData,  //提交参数
				success:function(response){
					btnObj.removeAttr('disabled');				
					if (response["code"] == 200){
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
					}
					else {
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
					};
					if ( order_type=='online'){
						document.getElementById("auditResultDiv").style.display = ""; 
						var resultHTML =  '<table class="table table-hover" id="auditResult">' +
	                    '<thead>' +
	                        '<tr>' +
	                            '<th>#</th>' +
	                            '<th>SQL</th>' +
	                            '<th>影响行</th>' +
	                            '<th>错误原因</th>' +
	                        '</tr>' +
	                	'</thead>' +
	                	'<tbody>'
					     var trHtml = ''
					     for (var i=0;i< response['data'].length;i++){
					    	 trHtml +=   '<tr>' + 
					                         '<td>'+ i +'</td>' + 
					                         '<td>'+ response['data'][i]['sql'] +'</td>' + 
					                         '<td>'+ response['data'][i]['row'] +'</td>' + 
					                         '<td>'+ response['data'][i]['errmsg'] +'</td>' + 
					                     '</tr>'
					     }
						resultHTML = resultHTML + trHtml + '</tbody></table>'
						$('#auditResult').html(resultHTML);		
					}
				},
		    	error:function(response){
		    		btnObj.removeAttr('disabled');
		    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
		    	}
			});	
		}
	

	


	
</script>

{% endblock %}
